import fs from 'fs-extra'
import path from 'path'

export const unlinkIfSymlink = async (target: string) => {
  // 获取完整的绝对路径
  const dst = path.resolve(process.cwd(), target)
  console.log('检查路径:', dst)

  try {
    // 检查路径是否存在
    const exists = await fs.pathExists(dst)
    console.log('路径是否存在:', exists)

    if (exists) {
      const stats = fs.lstatSync(dst)
      const isSymlink = stats.isSymbolicLink()
      console.log('是否是符号链接:', isSymlink)

      if (isSymlink) {
        // 获取符号链接指向的目标
        const linkTarget = await fs.readlink(dst)
        console.log('符号链接指向:', linkTarget)

        // 移除符号链接
        await fs.unlink(dst)
        console.log(`已解除符号链接：${dst}`)
      } else if (stats.isDirectory()) {
        // 如果是普通目录，也删除它
        await fs.remove(dst)
        console.log(`已删除普通目录：${dst}`)
      } else {
        console.log(`警告：${dst} 不是符号链接或目录`)
      }
    }
  } catch (e) {
    console.log(`处理路径时出错：${dst}`, e)
  }
}

export const copyDir = async (source: string, target: string) => {
  const src = path.resolve(process.cwd(), source)
  const dst = path.resolve(process.cwd(), target)

  try {
    // 检查源路径是否存在
    if (!(await fs.pathExists(src))) {
      console.log(`源路径不存在：${src}`)
      return
    }

    // 如果目标路径存在，先删除
    if (await fs.pathExists(dst)) {
      await fs.remove(dst)
      console.log(`已删除旧的目标目录：${dst}`)
    }

    // 复制文件夹
    await fs.copy(src, dst)
    console.log(`成功复制 ${src} 到 ${dst}`)
  } catch (e) {
    console.log('复制失败！', e)
  }
}

const main = async () => {
  const paths = ['apps/client/assets/scripts/proto', 'apps/client/assets/scripts/common']

  // 先解除所有可能存在的符号链接
  for (const p of paths) {
    console.log(`\n处理路径: ${p}`)
    await unlinkIfSymlink(p)
  }
  console.log('\n符号链接检查完成')

  // 复制文件
  await copyDir('apps/server/common/idl/auto-gen-ws', 'apps/client/assets/scripts/proto')
  console.log('同步proto文件')
  await copyDir('apps/server/common/common', 'apps/client/assets/scripts/common')
  console.log('同步common文件')
}

main()
